Máster en Data Science UAH

Tasador de viviendas de alquiler vacacional en Barcelona

Notebook #3 - Estudio de la localización

Alumno: Héctor Mateos Oblanca
Tutor: Daniel Rodríguez Pérez

Intro

In [1]:
city = 'barcelona'
month = '201909'
filename_in = 'src/data/' + city + '-' + month + '-listings-CLEAN.csv'
In [2]:
import math
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from IPython.display import display, HTML
import graphviz
from sklearn.tree import export_graphviz
import featuretools as ft
import uuid
import s2sphere as s2
import random
 
import catboost as cb
from kmodes.kmodes import KModes
from sklearn.ensemble import RandomForestRegressor
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.model_selection import train_test_split, GridSearchCV, cross_val_score, cross_val_predict 
from sklearn.metrics import r2_score, mean_squared_error, mean_absolute_error

import scipy.spatial as spatial
import plotly.express as px
import chart_studio.plotly as py
import plotly.graph_objs as go
from plotly.offline import iplot, init_notebook_mode

%run src/utils.py
In [3]:
coefs = {}
metrics = {}

def collect_results(columns, model, method, r2, mae, mse, skip_coef=True):
    # coefs
    if skip_coef != True:
        method_coefs = {}
        if hasattr(model, '__intercept'):
            method_coefs['__intercept'] = model.intercept_
        
        for i in range(len(columns.values)):
            method_coefs[columns.values[i]] = abs(model.coef_[i])
        coefs[method] = method_coefs
        df_coefs = pd.DataFrame(coefs)
        df_coefs = df_coefs.sort_values(by=method, ascending=False)
        display(df_coefs)
    
    # metrics
    metrics[method] = {
        'R2':r2.round(3),
        'MAE':mae.round(3),
        'MSE':mse.round(3)
    }
    
    display(pd.DataFrame(metrics))

def print_feature_importances(method, importances, df):
    feature_score = pd.DataFrame(list(zip(df.dtypes.index, importances)), columns=['Feature','Score'])
    feature_score = feature_score.sort_values(by='Score', 
                                              ascending=True, 
                                              inplace=False, 
                                              kind='quicksort', 
                                              na_position='last')
    
    fig = go.Figure(
        go.Bar(
            x=feature_score['Score'],
            y=feature_score['Feature'],
            orientation='h'
        )
    )
    
    fig.update_layout(
        title=method + " Feature Importance Ranking",
        height=25*len(feature_score)
    )
    
    fig.show()

Carga del dataset

In [4]:
df = pd.read_csv(filename_in)
df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 13109 entries, 0 to 13108
Data columns (total 61 columns):
host_response_time                      13109 non-null object
latitude                                13109 non-null float64
longitude                               13109 non-null float64
property_type                           13109 non-null object
room_type                               13109 non-null object
accommodates                            13109 non-null int64
bathrooms                               13109 non-null float64
bedrooms                                13109 non-null float64
price                                   13109 non-null float64
security_deposit                        13109 non-null float64
cleaning_fee                            13109 non-null float64
guests_included                         13109 non-null int64
extra_people                            13109 non-null float64
minimum_nights_avg_ntm                  13109 non-null float64
maximum_nights_avg_ntm                  13109 non-null float64
number_of_reviews                       13109 non-null int64
number_of_reviews_ltm                   13109 non-null int64
first_review                            13109 non-null object
last_review                             13109 non-null object
review_scores_rating                    13083 non-null float64
review_scores_accuracy                  13081 non-null float64
review_scores_cleanliness               13082 non-null float64
review_scores_checkin                   13080 non-null float64
review_scores_communication             13081 non-null float64
review_scores_location                  13079 non-null float64
review_scores_value                     13079 non-null float64
instant_bookable                        13109 non-null int64
cancellation_policy                     13109 non-null object
reviews_per_month                       13109 non-null float64
district                                13109 non-null object
neighbourhood                           13109 non-null object
has_wifi                                13109 non-null int64
has_essentials                          13109 non-null int64
has_kitchen                             13109 non-null int64
has_heating                             13109 non-null int64
has_washer                              13109 non-null int64
has_hangers                             13109 non-null int64
has_tv                                  13109 non-null int64
has_hair_dryer                          13109 non-null int64
has_iron                                13109 non-null int64
has_shampoo                             13109 non-null int64
has_laptop_friendly_workspace           13109 non-null int64
has_air_conditioning                    13109 non-null int64
has_hot_water                           13109 non-null int64
has_elevator                            13109 non-null int64
has_refrigerator                        13109 non-null int64
has_dishes_and_silverware               13109 non-null int64
has_microwave                           13109 non-null int64
has_bed_linens                          13109 non-null int64
has_no_stairs_or_steps_to_enter         13109 non-null int64
has_coffee_maker                        13109 non-null int64
has_cooking_basics                      13109 non-null int64
has_family/kid_friendly                 13109 non-null int64
has_long_term_stays_allowed             13109 non-null int64
has_first_aid_kit                       13109 non-null int64
has_oven                                13109 non-null int64
has_stove                               13109 non-null int64
has_license                             13109 non-null int64
activity_months                         13109 non-null float64
income_med_occupation                   13109 non-null float64
price_med_occupation_per_accommodate    13109 non-null float64
dtypes: float64(21), int64(32), object(8)
memory usage: 6.1+ MB

Descarte de características

In [5]:
useful_cols = [
    'accommodates',
    'bathrooms',
    'bedrooms',
    'cancellation_policy',
    'cleaning_fee',
    'extra_people',
    'guests_included',
    'has_air_conditioning',
    'has_bed_linens',
    'has_coffee_maker',
    'has_cooking_basics',
    'has_dishes_and_silverware',
    'has_elevator',
    'has_essentials',
    'has_family/kid_friendly',
    'has_first_aid_kit',
    'has_hair_dryer',
    'has_hangers',
    'has_heating',
    'has_hot_water',
    'has_iron',
    'has_kitchen',
    'has_laptop_friendly_workspace',
    'has_license',
    'has_long_term_stays_allowed',
    'has_microwave',
    'has_no_stairs_or_steps_to_enter',
    'has_oven',
    'has_refrigerator',
    'has_shampoo',
    'has_stove',
    'has_tv',
    'has_washer',
    'has_wifi',
    'instant_bookable',
    'latitude',
    'longitude',
    'maximum_nights_avg_ntm',
    'minimum_nights_avg_ntm',
    'neighbourhood',
    'price',
    'property_type',
    'room_type',
    'security_deposit'
]

useless_cols = [
    'district',
    'income_med_occupation',
    'activity_months',
    'host_response_time',
    'first_review',
    'last_review',
    'number_of_reviews',
    'number_of_reviews_ltm',
    'review_scores_rating',
    'review_scores_accuracy',
    'review_scores_cleanliness',
    'review_scores_checkin',
    'review_scores_communication',
    'review_scores_location',
    'review_scores_value',
    'reviews_per_month'
]

highly_corr_cols = [
    'has_refrigerator', 
    'host_verified_by_selfie'
]

df.drop([*useless_cols, *highly_corr_cols], axis=1, errors='ignore', inplace=True)
df.shape
Out[5]:
(13109, 44)

Nuevas características de localización calculadas

Distancia a puntos de interés

Se calcula para cada propiedad la distancia en kilómetros a diferentes puntos de interés turístico de la ciudad.

In [6]:
pois = [    
    {'name':'sants', 'coord':(41.37416517, 2.13749945)},
    {'name':'plaça-catalunya', 'coord':(41.387016, 2.170047)},
    {'name':'plaça-espanya', 'coord':(41.375148, 2.148426)},
    {'name':'estadio-camp-nou', 'coord':(41.380898, 2.122820)},
    {'name':'barceloneta', 'coord':(41.380894, 2.189385)},
    {'name':'montjuic', 'coord':(41.363485, 2.152609)}, 
    {'name':'parc-guell', 'coord':(41.4082, 2.1517)},
    {'name':'sagrada-familia', 'coord':(41.4036299, 2.1743558)},
    {'name':'casa-batllo', 'coord':(41.391640, 2.164770)},
    {'name':'drassanes-ramblas', 'coord':(41.376667, 2.175556)},
    {'name':'plaça-reial', 'coord':(41.380192, 2.175515)},
    {'name':'aeropuerto-prat', 'coord':(41.2974, 2.0833)}
]
In [7]:
for poi in pois:
    df['dist_' + poi['name']] = df.apply(
        lambda r: get_haversine_distance(
            r['latitude'], 
            r['longitude'], 
            poi['coord']), 
        axis=1)

Clustering de barrios

La característica neighbourhood tiene una cardinalidad muy alta que puede conducir a sobreajuste puesto que en algunos barrios hay pocos datos. Se propone, utilizando clusterización, una característica de cardinalidad intermedia entre barrios y distritos que agrupe barrios similares y que resulte más representativa para el estudio.

In [8]:
km = KModes(n_clusters=15, init='Huang', n_init=10, random_state=42)
df['nb_cluster'] = km.fit_predict(df[['price_med_occupation_per_accommodate', 'neighbourhood']])
clusters = df['nb_cluster'].copy()
df['nb_cluster'] = df['nb_cluster'].apply(lambda x: 'nb_' + str(x))
df.drop(['price_med_occupation_per_accommodate'], axis=1, inplace=True) # solo era para calcular clusters
In [9]:
cluster_map = pd.DataFrame(list(zip(df['neighbourhood'], clusters)), columns=['nb', 'cluster'])
cluster_map.drop_duplicates(inplace=True)

with open('src/geo/' + city + '.neighbourhoods.geojson') as f:
    city_nb = fix_geojson(json.load(f))
    
fig = go.Figure(go.Choroplethmapbox(
    geojson=city_nb,
    locations=cluster_map['nb'], 
    z=cluster_map['cluster'],                   
    colorscale=px.colors.qualitative.Vivid,                                
    marker_opacity=0.5, 
    marker_line_width=0.2
))

fig.update_layout(
    mapbox_style='carto-positron',
    mapbox_zoom=11, 
    mapbox_center={'lat':df['latitude'].mean(), 'lon':df['longitude'].mean()},
    margin={"r":0,"t":0,"l":0,"b":0},
    title='clusters',
    showlegend=False
)

fig.show()

Celdas S2

In [10]:
def get_s2(lat, lng):
    py_cellid = s2.CellId.from_lat_lng(
        s2.LatLng.from_degrees(lat, lng)
    )
    py_cellid = py_cellid.parent(12)
    return 's2_' + str(py_cellid.id())

df['s2'] = df.apply(lambda r: get_s2(r['latitude'], r['longitude']), axis=1)
In [11]:
df_s2 = df[['s2', 'latitude', 'longitude']]
s2_cells = sorted(df_s2['s2'].unique())
random.shuffle(s2_cells)
df_s2['idx'] = df_s2['s2'].apply(lambda x: s2_cells.index(x))
In [12]:
fig314 = go.Figure()

fig314.add_trace(go.Scattermapbox(
    lon=df_s2['longitude'],
    lat=df_s2['latitude'],
    mode='markers',
    marker_color=df_s2['idx'],
    text=df_s2['idx'],
    marker=dict(
        size=5,
        opacity=0.4,
        colorscale='spectral'
    )
))

fig314.update_layout(
    showlegend=False,
    mapbox_style='carto-positron',
    mapbox_zoom=11, 
    mapbox_center={'lat':df['latitude'].mean(), 'lon':df['longitude'].mean()},
    margin={"r":0,"t":0,"l":0,"b":0}
)

fig314.show()

Regiones Voronoi

In [13]:
poi_coords = list(map(lambda x: x['coord'], pois))
vor = spatial.Voronoi(poi_coords)

def get_voronoi_index(row):
    new_point = [row['latitude'], row['longitude']]
    point_index = np.argmin(np.sum((vor.points - new_point)**2, axis=1))
    return 'v_' + str(point_index)

df['voronoi'] = df.apply(lambda r: get_voronoi_index(r), axis=1)
spatial.voronoi_plot_2d(vor)
Out[13]:
In [14]:
df_voronoi = df[['voronoi', 'latitude', 'longitude']]
voronoi_cells = sorted(df_voronoi['voronoi'].unique())
df_voronoi['idx'] = df_voronoi['voronoi'].apply(lambda x: voronoi_cells.index(x))
In [15]:
fig315 = go.Figure()

fig315.add_trace(go.Scattermapbox(
    lon=df_voronoi['longitude'],
    lat=df_voronoi['latitude'],
    mode='markers',
    marker_color=df_voronoi['idx'],
    text=df_voronoi['idx'],
    marker=dict(
        size=5,
        opacity=0.4,
        colorscale='spectral'
    )
))

fig315.add_trace(
    go.Scattermapbox(
        lat=list(map(lambda x: x['coord'][0], pois)),
        lon=list(map(lambda x: x['coord'][1], pois)),
        text=list(map(lambda x: x['name'], pois)),
        mode='markers',
        marker=dict(
            size=8,
            opacity=0.9,
            color='black'
        )
    )
)

fig315.update_layout(
    showlegend=False,
    mapbox_style='carto-positron',
    mapbox_zoom=11, 
    mapbox_center={'lat':df['latitude'].mean(), 'lon':df['longitude'].mean()},
    margin={"r":0,"t":0,"l":0,"b":0}
)

fig315.show()

Conversión de características categóricas en dummies

In [16]:
print(df.shape)
dfd = pd.get_dummies(df)
print(dfd.shape)

target = 'price'
features = list(dfd.columns)
features.remove(target)
(13109, 58)
(13109, 193)

Partición en conjuntos de entrenamiento y test

In [17]:
x_train, x_test, y_train, y_test = train_test_split(
    dfd[features], 
    dfd[target],
    test_size=0.3,
    random_state=42
)

x_train = x_train.astype(float) # prevent conversion warnings

Modelo base: CatBoost

In [18]:
def eval_model(method, cols, df):
    model = cb.CatBoostRegressor(
        verbose=0, 
        random_seed=42, 
        depth=10, 
        iterations=150, 
        learning_rate=0.1
    )
    
    regressor = Pipeline([('model', model)])
    regressor.fit(x_train[cols], y_train)
    y_pred = regressor.predict(x_test[cols])
    r2 = r2_score(y_test, y_pred)
    mae = mean_absolute_error(y_test, y_pred)
    mse = mean_squared_error(y_test, y_pred)
    
    collect_results(cols, model, method, r2, mae, mse, skip_coef=True)
    importances = regressor.named_steps['model'].feature_importances_
    print_feature_importances(method, importances, df[cols])
    
    """
    tree_data = export_graphviz(
        regressor.named_steps['model'].estimators_[5], 
        feature_names=cols,
        filled=True
    )
    
    display(graphviz.Source(tree_data))
    """
    
    return y_pred

Estudio de la localización

In [19]:
neighbourhood_cols = [col for col in dfd if col.startswith('neighbourhood')]
dist_cols = [col for col in dfd if col.startswith('dist_')]
coord_cols = ['latitude', 'longitude']
nb_cluster_cols = [col for col in dfd if col.startswith('nb_cluster_')]
s2_cols = [col for col in dfd if col.startswith('s2_')]
voronoi_cols = [col for col in dfd if col.startswith('voronoi')]

Modelo sin variable geográfica

Este modelo registraría toda la variabilidad de precio que es debida a las propiedades de las viviendas sin considerar caractarísticas geográficas de ningún tipo.

In [20]:
cols = features.copy()
for c in [*neighbourhood_cols, *dist_cols, *coord_cols, *nb_cluster_cols, *s2_cols, *voronoi_cols]:
    if c in cols:
        cols.remove(c)
    
y_pred = eval_model('NO-GEO', cols, dfd)
NO-GEO
MAE 20.593
MSE 1235.301
R2 0.763

Residuos

Se busca si existen zonas con un error positivo o negativo.

  • Lo que se puede asociar con puntos de interés: positivo
  • Zonas que los visitantes prefieren evitar: negativo
In [21]:
x_test['resid'] = y_test - y_pred
plt.hist(x_test['resid'], bins=50)
plt.show()

Residuos outliers

In [22]:
x_test2 = x_test.copy()
x_test2.reset_index(inplace=True)
outliers_idx = get_outliers_iqr(x_test2['resid'])[0]
remove_outliers(x_test2, outliers_idx, 'resid')
outliers between following bounds: -50.508988258579166 46.27635281585837
341 outliers to be removed with values: [-159.48541648241894, -156.2673573487693, -149.9490810513048, -142.46443656960855, -137.52759712040614, -133.4111453384195, -131.01536800900195, -131.00243022018137, -122.612149218415, -114.33746209725666, -112.66728922465856, -105.76958302561391, -103.86335085496549, -102.57412319946673, -100.57518375525103, -99.84990621999985, -99.74185392997995, -97.12382161085998, -96.60789229045815, -95.7188437098061, -95.61571606604093, -94.39587586124345, -93.80943878420064, -93.78315439533802, -90.66749593424548, -90.46669331127956, -89.96997839701743, -87.73292333763493, -87.4399873228077, -86.55744025879036, -85.78346533435237, -85.22662691826395, -84.7658475959852, -84.40588884703618, -83.38878130510764, -83.34889699224391, -83.23521081232047, -83.12586198957456, -82.78208088791254, -82.57359252247699, -79.78232596571715, -77.37421315338898, -77.19993370438968, -76.55948526603778, -76.40574801140306, -75.31532945560706, -75.16631517606265, -74.33631928105477, -74.01237986142647, -73.97744605612291, -73.74657550044655, -73.3106182235305, -73.26911077078526, -72.98428484766268, -71.78412522925663, -71.3212805081101, -70.55027433869208, -70.36657153143801, -70.3496509968089, -69.20423460185475, -69.13582748660542, -69.05994590060837, -69.04503082385753, -68.24203064515599, -67.99418437935273, -67.71150673858502, -67.48629887296212, -67.31979367267449, -65.53818181658357, -65.18583639444336, -65.0949126211028, -64.91889709311195, -64.11694001592626, -63.05938617478827, -62.913120143089586, -62.89113160485647, -61.28617538961481, -60.83345842808896, -60.3488779621062, -60.01807968801134, -59.97109446931525, -59.56541094690945, -59.36430274240915, -58.749297458888506, -57.61650047877083, -57.14075657779037, -56.90667044043124, -56.73778026541894, -56.70639339975124, -56.40288886119734, -56.117418898199944, -56.02736191038868, -55.74733325936997, -55.49648438928904, -55.32292780079709, -55.10020699905928, -54.65355517096171, -54.435709106781616, -54.264134385206034, -54.2222468280293, -53.767052983773084, -53.760459389797845, -53.6026889077158, -53.099357325227004, -52.384023786089685, -52.354785776971994, -52.156467369699186, -52.050467189486696, -51.77713749030845, -51.57258754117797, -51.41790665149239, -51.37056801041639, -51.36327184363341, -51.17368472635325, -50.84433979342232, -50.79116096772172, -50.70728062515269, -50.58098777548781, -50.55741960230538, -50.55333301398858, -50.533982313139035, 46.335222620441385, 46.50511297019261, 46.696071615715226, 46.966302036992275, 47.30673895518609, 47.33133823250233, 47.381090862874785, 47.39160561467934, 47.46758594787568, 47.61031926749534, 47.622109994255645, 47.92387142010541, 48.017651711496526, 48.030005407428604, 48.535648310535365, 48.73591572087568, 48.81298534062553, 48.98970707245675, 49.29402868121969, 49.34198445210393, 49.70295210207424, 49.83551049166137, 49.95269502398138, 50.17438199660873, 50.26888799429716, 50.344865060549566, 50.638565818159705, 51.10962289171162, 51.27748472781843, 51.454847815844275, 51.58227608347616, 51.8016535143276, 51.986817380269585, 52.00091442092298, 52.17511114819101, 52.23323089553144, 52.240080214607445, 52.24762581545579, 52.6068046421542, 52.63104619954469, 52.7781732994262, 52.85105044769534, 52.91956586787046, 53.33176182591345, 53.421393409080196, 53.830131972033655, 54.8601298673987, 55.45571213623731, 55.552050721153705, 55.6467450318101, 55.78984659216252, 55.88563858643472, 56.1970130198374, 56.3171536699613, 57.04433002814878, 57.59050787909814, 58.4148344876794, 58.52363580209433, 58.54865701185125, 58.76886073148799, 58.87139102373712, 58.95985785501252, 59.33065101685878, 59.608137759404144, 60.06228749879594, 60.38836178314102, 60.923557734902744, 61.08201998231527, 61.43098187497722, 61.82936119440552, 61.93515649862451, 62.004531916330876, 62.60280910631654, 62.92874360869071, 63.30035742605969, 63.637611173302716, 64.1616998196611, 64.47906395254952, 64.58663268903499, 65.42815442810402, 65.69611823101596, 65.99412820791706, 66.50729609633021, 66.9526901401835, 67.05583882626303, 67.20641681139517, 67.61015463210427, 67.82915071082864, 67.96135592439427, 68.20763443284115, 68.33911644639588, 68.50550461714678, 68.77739429380043, 69.14015976032479, 69.24065651723853, 69.68905524358519, 70.08505513938135, 70.66264419279761, 71.2062762169657, 71.72378398091158, 72.21070216925348, 72.24676982929901, 73.89805627779364, 73.93677631001836, 74.03863500336664, 74.77196339079302, 75.01249187930262, 75.87365897874201, 75.89635762766554, 76.45937461533919, 76.57337355605036, 77.92700073852642, 78.05367577724033, 78.25714891350799, 78.40481107547052, 79.23551968734088, 79.291905682368, 79.29465360676389, 79.6732925428828, 80.21246032529073, 80.28776795865053, 80.40488597979332, 80.69331151936457, 81.49865874617116, 81.9076448164245, 82.00458333575347, 82.38720999386904, 82.3888298040075, 82.63563208585936, 83.10245779477683, 83.15667876865973, 83.79312744148791, 84.94681380484435, 84.9539819334843, 87.3261088234546, 88.57835637950953, 88.69185997256272, 89.10223014924108, 90.43362187281916, 90.50757241063266, 91.60531327136829, 91.88734116490755, 91.9423069172712, 92.52137610440933, 93.0473080021143, 93.87359583208791, 94.18260970315603, 94.27444907850683, 94.86918256714694, 95.91761569084653, 98.3442938114963, 98.8116399721451, 100.68822009023773, 101.30668930872085, 101.87555368338934, 102.58801447351684, 103.37509272712609, 103.73018521630652, 104.04512212106522, 104.89070316536859, 105.06920171070874, 106.39001705941325, 107.22777801343044, 107.74233184762309, 108.91749256296778, 111.0317589053339, 111.89426855424995, 113.52691637921777, 114.95962750828316, 118.88756218194736, 119.35197455923375, 119.41462509459953, 120.55337518213278, 121.08226985436073, 122.80242466560688, 123.07613953092576, 124.35192122284201, 127.00760403006524, 127.16454356706285, 128.4080710711711, 131.3604257321845, 131.8596682210403, 132.76648364357135, 135.105869814375, 135.98304329013732, 139.58513161691252, 144.87999618705362, 146.3734208808304, 149.99997949770554, 152.4307927698169, 152.5294090542102, 155.2808075248793, 156.74821628319233, 158.95501418194164, 162.89353102944494, 170.96924162161685, 172.2113956268693, 173.05168582318808, 173.78339194010044, 175.58876058965393, 176.48396093759754, 178.10187739810246, 179.86276559385345, 182.49828741668102, 184.50479458873482, 190.73681205297032, 192.3679599624825, 202.9235393495777, 210.63953139962783, 221.08268994542317, 228.5947743862137, 233.09228761195106, 251.16019035487415, 254.26664309235957, 272.98175399990856, 291.0129330179948, 701.7460496585205]
In [23]:
plt.hist(x_test2['resid'], bins=30)
plt.show()
In [24]:
fig1 = go.Figure(
    go.Scattermapbox(
        lon=x_test2['longitude'],
        lat=x_test2['latitude'],
        mode='markers',
        marker_color=x_test2['resid'],
        text=x_test2['resid'],
        marker=dict(
            opacity=0.8,
            colorscale=[
                [0.0, "rgb(165,0,38)"],
                [0.11, "rgb(215,48,39)"],
                [0.22, "rgb(244,109,67)"],
                [0.33, "rgb(253,174,97)"],
                [0.44, "rgb(254,224,144)"],
                [0.55, "rgb(224,243,248)"],
                [0.66, "rgb(171,217,233)"],
                [0.77, "rgb(116,173,209)"],
                [0.88, "rgb(69,117,180)"],
                [1.0, "rgb(49,54,149)"]
            ]
        )
    )
)

fig1.update_layout(
    mapbox_style='carto-positron',
    mapbox_zoom=11, 
    mapbox_center={'lat':x_test2['latitude'].mean(), 'lon':x_test2['longitude'].mean()},
    margin={"r":0,"t":0,"l":0,"b":0}
)

fig1.show()

Coordenadas

In [25]:
cols = features.copy()
for c in [*neighbourhood_cols, *dist_cols, *nb_cluster_cols, *s2_cols, *voronoi_cols]:
    if c in cols:
        cols.remove(c)
    
y_pred = eval_model('COORD', cols, dfd)
NO-GEO COORD
R2 0.763 0.780
MAE 20.593 19.913
MSE 1235.301 1149.336

Barrios

In [26]:
cols = features.copy()
for c in [*dist_cols, *coord_cols, *nb_cluster_cols, *s2_cols, *voronoi_cols]:
    if c in cols:
        cols.remove(c)
    
y_pred = eval_model('NB', cols, dfd)
NO-GEO COORD NB
R2 0.763 0.780 0.771
MAE 20.593 19.913 20.176
MSE 1235.301 1149.336 1192.224

Cluster de barrios

In [27]:
cols = features.copy()
for c in [*neighbourhood_cols, *dist_cols, *coord_cols, *s2_cols, *voronoi_cols]:
    if c in cols:
        cols.remove(c)
    
y_pred = eval_model('CLUSTER-NB', cols, dfd)
NO-GEO COORD NB CLUSTER-NB
R2 0.763 0.780 0.771 0.769
MAE 20.593 19.913 20.176 20.188
MSE 1235.301 1149.336 1192.224 1206.079

Distancias a puntos de interés

In [28]:
cols = features.copy()
for c in [*neighbourhood_cols, *coord_cols, *nb_cluster_cols, *s2_cols, *voronoi_cols]:
    if c in cols:
        cols.remove(c)
    
y_pred = eval_model('DIST', cols, dfd)
NO-GEO COORD NB CLUSTER-NB DIST
R2 0.763 0.780 0.771 0.769 0.775
MAE 20.593 19.913 20.176 20.188 20.016
MSE 1235.301 1149.336 1192.224 1206.079 1172.636

Voronoi

In [29]:
cols = features.copy()
for c in [*neighbourhood_cols, *nb_cluster_cols, *coord_cols, *dist_cols, *s2_cols]:
    if c in cols:
        cols.remove(c)
    
y_pred = eval_model('VORONOI', cols, dfd)
NO-GEO COORD NB CLUSTER-NB DIST VORONOI
R2 0.763 0.780 0.771 0.769 0.775 0.769
MAE 20.593 19.913 20.176 20.188 20.016 20.431
MSE 1235.301 1149.336 1192.224 1206.079 1172.636 1206.753

S2

In [30]:
cols = features.copy()
for c in [*neighbourhood_cols, *nb_cluster_cols, *coord_cols, *dist_cols, *voronoi_cols]:
    if c in cols:
        cols.remove(c)
    
y_pred = eval_model('S2', cols, dfd)
NO-GEO COORD NB CLUSTER-NB DIST VORONOI S2
R2 0.763 0.780 0.771 0.769 0.775 0.769 0.762
MAE 20.593 19.913 20.176 20.188 20.016 20.431 20.265
MSE 1235.301 1149.336 1192.224 1206.079 1172.636 1206.753 1239.405

Balanceo undersampling por cluster de barrios

In [31]:
df_us = df.copy().sample(frac=1, random_state=42)
df_us.shape
Out[31]:
(13109, 58)
In [32]:
def get_max_sample_size(df):
    df_by_cluster = df_us.groupby(['nb_cluster'])['nb_cluster'].count().to_frame('count')
    df_by_cluster.reset_index(inplace=True)
    return min(df_by_cluster['count'])

def print_cluster_dist(df):
    df_by_cluster = df.groupby(['nb_cluster'])['nb_cluster'].count().to_frame('count')
    df_by_cluster.reset_index(inplace=True)
    df_by_cluster.sort_values(by=['count'], inplace=True)
    fig = px.bar(df_by_cluster, x='nb_cluster', y='count')
    fig.show()
In [33]:
print_cluster_dist(df_us)

for c in [13, 8, 14, 12, 4, 7, 5]:
    val = 'nb_' + str(c)
    df_us['nb_cluster'][df_us['nb_cluster'] == val] = 'nb_other'
    
print_cluster_dist(df_us)
In [34]:
sample_size = get_max_sample_size(df_us)
print(sample_size)
parts = []

for c in np.unique(df_us['nb_cluster']):
    x_tmp = df_us.loc[df_us['nb_cluster'] == c].sample(n=sample_size, random_state=42)
    parts.append(x_tmp)
    
df_us = pd.concat(parts)

print_cluster_dist(df_us)
684
In [35]:
df_us = pd.get_dummies(df_us)

target = 'price'
features = list(df_us.columns)
features.remove(target)
In [36]:
x_train, x_test, y_train, y_test = train_test_split(
    df_us[features], 
    df_us[target],
    random_state=42
)

x_train = x_train.astype(float) # prevent conversion warnings
In [37]:
y_pred = eval_model('CLUSTER-UNDERSAMP', x_train.columns, df_us)
NO-GEO COORD NB CLUSTER-NB DIST VORONOI S2 CLUSTER-UNDERSAMP
R2 0.763 0.780 0.771 0.769 0.775 0.769 0.762 0.741
MAE 20.593 19.913 20.176 20.188 20.016 20.431 20.265 21.847
MSE 1235.301 1149.336 1192.224 1206.079 1172.636 1206.753 1239.405 1555.187

Automated feature engineering

In [38]:
auto_df = df.copy()
auto_df['auto_id'] = auto_df['price'].apply(lambda x: uuid.uuid1().int)
prices = auto_df['price']
auto_df.drop(['price'], axis=1, inplace=True, errors='ignore')
In [39]:
es = ft.EntitySet(id='airbnb')
es = es.entity_from_dataframe(
    entity_id='main',
    dataframe=auto_df,
    index='auto_id'
)
In [40]:
# available_transform_primitives = ft.primitives.list_primitives()
# print(available_transform_primitives[available_transform_primitives['type'] == 'transform'])

features_df, feature_names = ft.dfs(
    entityset=es,
    target_entity='main',
    trans_primitives=['subtract_numeric'],
    max_depth=2
)

# print(features_df.columns)
In [41]:
auto_df = features_df.copy()
auto_df.reset_index()
auto_df.drop(['auto_id'], axis=1, inplace=True, errors='ignore')

auto_df = pd.get_dummies(auto_df)
print(auto_df.shape)

auto_features = list(auto_df.columns)

x_train, x_test, y_train, y_test = train_test_split(
    auto_df, 
    prices,
    random_state=42
)

x_train = x_train.astype(float) # prevent conversion warnings
(13109, 1417)
In [42]:
y_pred = eval_model('AUTO-FT', auto_features, auto_df)
NO-GEO COORD NB CLUSTER-NB DIST VORONOI S2 CLUSTER-UNDERSAMP AUTO-FT
R2 0.763 0.780 0.771 0.769 0.775 0.769 0.762 0.741 0.761
MAE 20.593 19.913 20.176 20.188 20.016 20.431 20.265 21.847 20.161
MSE 1235.301 1149.336 1192.224 1206.079 1172.636 1206.753 1239.405 1555.187 1207.033